package com.stock.security.service;

import com.google.common.base.Strings;
import com.stock.domain.vo.response.PermissionRespNodeVo;
import com.stock.mapper.SysRoleMapper;
import com.stock.mapper.SysUserMapperExt;
import com.stock.pojo.entity.SysPermission;
import com.stock.pojo.entity.SysRole;
import com.stock.pojo.entity.SysUser;
import com.stock.security.user.LoginUserDetail;
import com.stock.service.PermissionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

// TODO 定义获取用户详情服务bean
@Service("loginUserDetailService")
public class LoginUserDetailService implements UserDetailsService {

    @Autowired
    private SysUserMapperExt sysUserMapperExt;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    // TODO 根据传入的用户的名称获取用户相关详情信息，密文密码，权限集合等。
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名获取用户详情信息
        SysUser dbUser = sysUserMapperExt.findUserByUserName(username);
        if (dbUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 获取指定用户的权限集合
        List<SysPermission> permissions = permissionService.getPermissionByUserId(dbUser.getId());
        // 获取指定用户的角色集合
        List<SysRole> roles = sysRoleMapper.getRoleByUserId(dbUser.getId());
        // 获取树状权限菜单数据
        List<PermissionRespNodeVo> menus = permissionService.getTree(permissions, 0L, true);
        // 获取菜单按钮集合
        List<String> authBtnPerms = permissions.stream()
                .filter(per -> !Strings.isNullOrEmpty(per.getCode()) && per.getType() == 3)
                .map(per -> per.getCode())
                .collect(Collectors.toList());

        // 获取Spring Security需要的权限标识
        ArrayList<String> ps = new ArrayList<>();
        List<String> pers = permissions.stream()
                .filter(per -> StringUtils.isNotBlank(per.getCode()))
                .map(per -> per.getPerms())
                .collect(Collectors.toList());
        ps.addAll(pers);
        List<String> rs = roles.stream()
                .map(role -> "ROLE_" + role.getName())
                .collect(Collectors.toList());
        ps.addAll(rs);

        // 将用户拥有的权限标识转成权限对象
        String[] psArray = ps.toArray(new String[pers.size()]);
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(psArray);

        // 构建用户详情服务对象
        LoginUserDetail userDetail = new LoginUserDetail();
        // 拷贝用户信息 将数据库用户信息拷贝到用户详情对象中
        BeanUtils.copyProperties(dbUser, userDetail);
        // 设置树状权限菜单集合
        userDetail.setMenus(menus);
        // 设置按钮权限集合
        userDetail.setPermissions(authBtnPerms);
        // 设置权限对象集合
        userDetail.setAuthorities(authorities);
        return userDetail;
    }
}
